<?php
namespace app\wx_api\controller;

use app\wx_api\ext\we_chat\AccessTokenCache;
use app\wx_api\ext\we_chat\UserMsg;
use app\wx_api\ext\auth\Token;
use app\wx_api\ext\we_chat\WXConfig;
use app\wx_api\model\UserModel;
use think\Controller;
use think\Exception;

/**
 * 微信授权登录
 *
 * Class AuthController
 * @package app\api\controller
 */
class LoginController extends Controller
{
    // 微信网页授权的触发api
    const AUTH_LOGIN_START_API = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";

    /**
     * 微信客户端授权登录，引导和触发用户授权的流程的起点
     */
    public function index() {
        $wx_id = input('wx_id', ''); // 微信在平台注册的ID
        $plat_id = input('plat_id', ''); // 平台ID

        if (empty($wx_id) || empty($plat_id)) {
            throw new Exception('没有参数wx_id或者plat_id，请传递注册在平台的微信id');
        }
        $url = self::AUTH_LOGIN_START_API;
        $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . '/wx_api/login/call_back/wx_id/' . $wx_id . '/plat_id/' . $plat_id;
        //var_dump($redirect_url);die;
        //$u = "https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60";

        $wx_config = WXConfig::wxConfig($wx_id);
        if (empty($wx_config)) {
            throw new Exception('请在平台完成微信信息的注册');
        }
        $app_id = $wx_config['app_id'];
        //var_dump($redirect_url, urlencode($url));die;
        $url = sprintf($url, $app_id, urlencode($redirect_url));
        //var_dump($url);die;
        //header('location:'. $url);
        header("location:$url");
        exit();
    }

    /**
     * 微信授权登录的回调，据说这里
     * 不需要返回操作。
     * 实践证明这里需要返回，因为，这里是用户在
     * 微信端授权完成后回调此action并且最终的动作
     * 由该action决定。
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function call_back()
    {
        $data = $this->request->param();
        //var_dump($data);die;
        if ($data['code']) {
            $wx_id = input('wx_id', '');
            $wx = WXConfig::wxConfig($wx_id);
            if (empty($wx)) {
                //var_dump('wx');die;
                $this->assign('err_msg', '没有找到对应的微信信息');
                return $this->fetch('login/error');
            }
            $plat_id = input('plat_id', '');
            if (empty($wx_id) || empty($plat_id)) {
                $this->assign('err_msg', '没有传递必要的参数wx_id或者plat_id');
                return $this->fetch('login/error');
            }
            // 获取access_token的接口调用
            $userMsgM = new UserMsg();
            if (!$res_data = $userMsgM->userToken($data['code'], $wx_id)) {
                //var_dump($res_data);die;
                $this->assign('err_msg', $userMsgM->err_msg);
                return $this->fetch('login/error');
            }
            // 获取微信用户的详情
            if(!$user_info_res = $userMsgM->userInfo($res_data['openid'], $res_data['access_token'])) {
                $this->assign('err_msg', $userMsgM->err_msg);
                return $this->fetch('login/error');
            }
            // 用户数据入库
            $userM = new UserModel();
            // 用于维持用户会话的token
            $tokenM = new Token();
            $session_token = $tokenM->generateToken($user_info_res['openid']);
            $data = [
                'open_id' => $user_info_res['openid'],
                'wx_id' => $wx_id,
                'wechat_no' => $wx['wechat_no'],
                'plat_id' => $plat_id,
                'nick_name' => $user_info_res['nickname'],
                'avatar_url' => $user_info_res['headimgurl'],
                'gender' => $user_info_res['sex'],
                'country' => $user_info_res['country'],
                'province' => $user_info_res['province'],
                'city' => $user_info_res['city'],
                'token' => $session_token,
                'updated_time' => date('Y-m-d H:i:s'),
            ];
            // 保存或者更新微信用户信息
            if (!$userM->saveUser($data)) {
                $this->assign('err_msg', '服务器繁忙！请联系客服');
                return $this->fetch('login/error');
            }
            // 授权成功返回页面
            return $this->fetch();
        } else {
            $this->assign('err_msg', '非法访问');
            return $this->fetch('login/error');
        }
    }

    /**
     * 测试获取微信通用access_token
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function auth_token() {
        $accessTokenM = new AccessTokenCache();
        if ($token = $accessTokenM->getAccessToken(1)) {
            var_dump($token);
        } else {
            var_dump($accessTokenM->err_msg);
        }

    }


}
